#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <mqueue.h>

#include "config.h"
#include "balr_demarrage.h"


void* BALRdemarrage()
{
	// Initialisation -----------------------------------------------
	mqd_t queue_demarrage;
	int reading_size;
	MSG_demarrage msg_demarrage;

	// opening "BAL_demarrage", READ only
	queue_demarrage = mq_open(BAL_demarrage, O_RDONLY);



	// Running loop -------------------------------------------------

	for(;;)
	{
		// waiting for a msg
		reading_size = mq_receive(queue_demarrage, (const char*) &msg_demarrage, sizeof(MSG_demarrage), NULL);
		
		if(reading_size == -1)
		{
			perror("[BAL_Demarrage] Failed to receive msg from BAL_demarrage:");
		}
		else
		{
			// Reading the msg
			printf("[BAL_Demarrage] Received order to start production.\n\n");
			
			// Reading OF into shared memory:
			pthread_mutex_lock(MutexSHMOF);
			int nbBatch = OrdreFabrication->numLot;
			int nbPal_A = OrdreFabrication->nbPaletteA;
			int nbBox_A = OrdreFabrication->taillePaletteA;
			int nbProd_A = OrdreFabrication->tailleCartonA;
			int nbPal_B = OrdreFabrication->nbPaletteB;
			int nbBox_B = OrdreFabrication->taillePaletteB;
			int nbProd_B = OrdreFabrication->tailleCartonB;
			pthread_mutex_unlock(MutexSHMOF);	

			printf("[BAL_Demarrage] OF in Shared Memory is defined like this:\n- batch = %d\n- nb pal A = %d\n- nb box A = %d\n- nb prod A = %d\n- nb pal B = %d\n- nb box B = %d\n- nb prod B = %d\n\n", nbBatch, nbPal_A, nbBox_A, nbProd_A, nbPal_B, nbBox_B, nbProd_B);
		}
	}
}
